import {defineStore} from "pinia";
import {adminLogin, studentLogin} from "@/api/login/login.ts";
import {ApiResponse} from "@/utils/request.ts";
import {queryUserBaseInfoByToken} from "@/api/user/user.ts";
import {userBaseInfo} from "@/store/modules/type/type.ts";
import {
    getBaseUserInfo,
    getToken,
    removeBaseUserInfo,
    removeMenuList,
    removeToken,
    setBaseUserInfo,
    setToken
} from "@/utils/token.ts";

const useUserStore = defineStore('userStore', {
    state: () => {
        return {
            token: getToken(),
            expiration: 0,
            authHeader: '',
            tokenHeader: '',
            userBaseInfo: getBaseUserInfo(),
            buttons: []
        }
    },
    actions: {
        async adminLogin(data: any) {
            const result: ApiResponse<any> = await adminLogin(data)
            if (result.code === 1000_0000) {
                //pinia仓库存储一下token
                const resultData = result.data
                //本地存储持久化存储一份
                this.authHeader = resultData.authHeader
                this.tokenHeader = resultData.tokenHeader
                this.expiration = resultData.expiration
                this.token = resultData.token
                setToken(resultData.token);
            }
        },
        async studentLogin(data: any) {
          const result: ApiResponse<any> = await studentLogin(data)
            if (result.code === 1000_0000) {
                //pinia仓库存储一下token
                const resultData = result.data
                //本地存储持久化存储一份
                this.authHeader = resultData.authHeader
                this.tokenHeader = resultData.tokenHeader
                this.expiration = resultData.expiration
                this.token = resultData.token
                setToken(resultData.token);
            }
        },
        async getUserInfo() {
            const result: ApiResponse<any> = await queryUserBaseInfoByToken()
            if (result.code === 1000_0000) {
                this.userBaseInfo = result.data as userBaseInfo
                setBaseUserInfo(result.data)
            }
        },
        userLogout() {
            this.token = ''
            this.expiration = 0
            this.authHeader = ''
            this.tokenHeader = ''
            this.userBaseInfo = {}
            removeToken()
            removeMenuList()
            removeBaseUserInfo()
        },
    },
    persist: true
})

export default useUserStore
